import { useRequest } from 'ahooks';
import { Button, Divider, Empty, Form, Input, Spin, Typography } from 'antd';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

import { PrismCode } from '@/components/SourceCode';
import { VulnerableProps } from '@/components/VulnerableTemplate/type';
import xssCode from '@/pages/vulnerable/code/xss';
import { judgeScript } from '@/utils/judgeAttack';
import messageBox from '@/utils/messageBox';

import { addMessage, getMessage, MessageType, removeMessage } from '../../service';

const { Title } = Typography;

const codeProps: PrismCode = {
  language: 'tsx',
  code: xssCode.store,
};

const Vulnerable: React.FC = () => {
  const [dataSource, setDataSource] = useState<MessageType[]>([]);
  const [form] = Form.useForm();
  const { t } = useTranslation();

  // 获取/刷新留言
  const { loading, refresh } = useRequest<any, any>(async () => {
    const result = await getMessage();
    setDataSource(result);
    form.resetFields();
  });

  // 添加留言
  const { run: addMsg } = useRequest(
    async () => {
      const { title, content } = form.getFieldsValue(['title', 'content']);
      if (judgeScript([title, content])) {
        messageBox.info({ content: t('xss.insertScript') });
      }
      await addMessage({ title, content }).then(res => setDataSource(res));
    },
    { manual: true },
  );

  // 清空留言
  const { run: clearMsg } = useRequest(
    async () => {
      await removeMessage().then(() => setDataSource([]));
    },
    { manual: true },
  );

  return (
    <section className="flex ldpi:flex-col">
      <div className="flex-1 pr-5">
        <Title italic level={4}>
          {t('xss.store.title')}
        </Title>
        <Form layout="vertical" form={form} labelAlign="left" labelCol={{ span: 4 }}>
          <Form.Item name="title" className="mb-0" label={t('title')} required>
            <Input maxLength={20} />
          </Form.Item>
          <Form.Item name="content" className="mb-0" label={t('message')} required>
            <Input.TextArea />
          </Form.Item>
          <Button.Group className="mt-2">
            <Button onClick={addMsg}>{t('add')}</Button>
            <Button onClick={clearMsg}>{t('clear')}</Button>
            <Button onClick={refresh}>{t('refresh')}</Button>
          </Button.Group>
        </Form>
      </div>
      <Divider className="ldpi:block hdpi:hidden" />
      <div className="flex-1 sm:mt-4">
        <Title level={4} italic>
          {t('xss.store.message')}
        </Title>
        <Spin spinning={loading}>
          <div className="max-h-[560px] overflow-scroll">
            {dataSource.length === 0 && (
              <Empty
                style={{ color: 'var(--empty-font)' }}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={t('empty')}
              />
            )}
            {dataSource.map((m, idx) => (
              <div key={idx} className="p-3 border">
                <h5 dangerouslySetInnerHTML={{ __html: m.title }} />
                <p dangerouslySetInnerHTML={{ __html: m.content }} />
              </div>
            ))}
          </div>
        </Spin>
      </div>
    </section>
  );
};

const XssStore: VulnerableProps = {
  vulnerable: <Vulnerable />,
  codeProps,
  causesSolutions: {
    type: 'xss',
    hasCompare: true,
    solutions: 5,
  },
};

export default XssStore;
